const {
  queryList,
  modifyService,
  addService,
  queryInfoService,
  deleteService,
  deleteSelectService,
} = require("../service/tag.service");
const {
  TagModifyError,
  TagAddError,
  DeleteError,
} = require("../constant/err.type");
class tagController {
  async queryTagList(ctx, next) {
    let res;
    try {
      res = await queryList(ctx.request.body);
      ctx.body = {
        code: 200,
        message: "获取标签列表成功",
        data: res.data,
        pageSize: res.pageSize,
        currentPage: res.currentPage,
        totalPage: Math.ceil(res.total / res.pageSize),
        total: res.total,
      };
    } catch (error) {
      console.log(error,"error")
    }
  }

  async modifyTag(ctx, next) {
    const { id, tagName } = ctx.request.body;
    const [a, row] = await modifyService({ id, tagName });
    console.log(row, "row");
    if (row >= 0) {
      ctx.body = {
        code: 200,
        message: "修改成功",
        data: null,
      };
    } else {
      console.error("row小于0,未修改");
      ctx.app.emit("error", TagModifyError, ctx);
    }
  }

  async addControll(ctx, next) {
    const { tagName } = ctx.request.body;
    try {
      const [id, row] = await addService({ tagName }, ctx);
      if (row > 0) {
        ctx.body = {
          code: 200,
          message: "添加成功",
          data: null,
        };
      } else {
        console.error("row小于等于0,添加失败");
        ctx.app.emit("error", TagAddError, ctx);
      }
    } catch (error) {
      ctx.app.emit("error", TagAddError, ctx);
    }
  }
  async queryTagByIdControl(ctx, next) {
    const { id } = ctx.query;
    console.log(ctx.query, "query");
    const res = await queryInfoService(id);
    ctx.body = {
      code: 200,
      message: "请求成功",
      data: res,
    };
  }

  async deleteControl(ctx, next) {
    console.log(ctx.request.body);
    if (ctx.request.body && ctx.request.body.id) {
      try {
        const { id } = ctx.request.body;
        await deleteService({ id });
        ctx.body = {
          code: 200,
          message: "删除成功",
          result: null,
        };
      } catch (error) {
        ctx.app.emit("error", DeleteError, ctx);
      }
    }
  }
  async deleteSelectControl(ctx, next) {
    let str = ctx.request.body.ids;
    const ids = str.split(",");
    try {
      await deleteSelectService(ids);
      ctx.body = {
        code: 200,
        message: "删除成功",
        result: null,
      };
    } catch (error) {
      ctx.app.emit("error", DeleteError, ctx);
    }
  }
}

module.exports = new tagController();
